from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView
from django.shortcuts import render, redirect
from django.contrib import auth

from ..models import UserProfile
from ..forms import UserForm, UserProfileForm
from .api import *


@login_required
def index(request):
    return redirect("mydoctor:data")


class Chat(LoginRequiredMixin, TemplateView):
    template_name = "chat.html"

    def get(self, request, qa_id=0, *args, **kwargs):
        print(qa_id)
        return super().get(request, qa_id=qa_id, *args, **kwargs)


class Data(LoginRequiredMixin, TemplateView):
    template_name = "data.html"


class SignupView(TemplateView):
    template_name = "signup.html"

    def get(self, request, *args, **kwargs):
        return super().get(
            request,
            user_form=UserForm(),
            user_profile_form=UserProfileForm(),
        )

    def post(self, request, *args, **kwargs):
        user_form = UserForm(request.POST)
        user_profile_form = UserProfileForm(request.POST)
        if user_form.is_valid() and user_profile_form.is_valid():
            user = user_form.save()
            user.refresh_from_db()
            user_profile = UserProfile(user=user)
            user_profile_form = UserProfileForm(
                request.POST,
                instance=user_profile,
            )
            user_profile = user_profile_form.save()
            user.save()
            auth.login(request, user)
            return redirect("mydoctor:profile:index")
        else:
            ctx = {}
            ctx["msg"] = "Please fix the form."
            return render(request, self.template_name, ctx)
